

package com.aspire.nm.component.cmppserver.runTime.moProcess.queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;



@Scope("prototype")
@Component
public class MOQueue<T> implements InitializingBean{
	
	@Value("${cmppserver.moQueueSize}")
	private int moQueueSize;
	
	private BlockingQueue<T> queue;
	private BlockingQueue<T> backQueue;
	
	
	
	@Override
	public void afterPropertiesSet() throws Exception {
		queue = new ArrayBlockingQueue<T>(moQueueSize);
		backQueue = new ArrayBlockingQueue<T>(moQueueSize);
	}
	
	
	
	
	/**
	 * 加入对象
	 * 
	 * @param o
	 */
	public void put(T e) throws InterruptedException{
		queue.put(e);
	}
	
	public boolean offer(T e){
	    return queue.offer(e);
	}

    
	/**
	 * 取出对象
	 * @return
	 * @throws InterruptedException
	 */
	public  T take() throws InterruptedException {
		T ret = backQueue.poll();
		return ret != null ? ret : queue.take();
	}
	
	/**
	 * 取得队列中存在对象数量
	 * 
	 * @return 队列中对象数量
	 */
	public int size(){
		return queue.size() + backQueue.size();
	}
	public int queueSize(){
		return queue.size() ;
	}
	
	/**
	 * 取得可用空间
	 * @return 可用空间
	 */
	public int remainingCapacity(){
		return queue.remainingCapacity();
	}
	
	/**
	 * 清空队列
	 */
	public void clear(){
		queue.clear();
		backQueue.clear();
	}
	
	/**
	 * 将之前去除的元素退回
	 * @param e
	 */
	public  boolean putBack(T e){		
		return backQueue.offer(e);
	}

	
}
